<?php

namespace App\Http\Controllers\Admin\Finance\Payable;

use App\Http\Controllers\Controller;
use App\Models\AgentModel;
use App\Models\finance\PayableAirlineModel;
use App\Models\TakeOrderModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class Airline extends Controller
{
    /**
     * 航司运费列表
     */
    public function list(Request $request)
    {
        $take_order = trim($request->input('take_order', ''));
        $agent_id = $request->input('agent_id', 0);
        $origin = $request->input('origin', '');
        $destination = $request->input('destination', '');
        $flight_date_start = $request->input('flight_start', '');
        $flight_date_end = $request->input('flight_end', '');
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);

        $query = PayableAirlineModel::with(['agent', 'takeOrder', 'createAdmin']);

        if ($take_order) {
            $query->whereHas('takeOrder', function ($query) use ($take_order) {
                $query->where('sn', $take_order);
            });
        }

        if ($origin) {
            $query->where('origin', $origin);
        }

        if ($destination) {
            $query->where('destination', $destination);
        }

        if ($agent_id) {
            $query->where('agent_id', $agent_id);
        }

        if ($flight_date_start && $flight_date_end) {
            $query->whereBetween('flight_date', [$flight_date_start, $flight_date_end]);
        }

        $total = $query->count();
        $items = $query->orderBy('id', 'desc')
            ->offset(($page - 1) * $limit)
            ->limit($limit)
            ->get()->map(function ($item) {
                //供应商名称	航班日期	主单号	件数	始发地	目的地	重量	计费重量	单价	运费金额	舱单费	分单费	其他杂费	币别
                return [
                    'id' => $item->id,
                    'agent_id' => $item->agent_id,
                    'agent_name' => $item->agent->name ?? '',
                    'flight_date' => $item->flight_date,
                    'take_order' => $item->takeOrder->sn ?? '',
                    'package_num' => $item->package_num,
                    'origin' => $item->origin,
                    'destination' => $item->destination,
                    'weight' => $item->weight,
                    'charge_weight' => $item->charge_weight,
                    'unit_price' => $item->unit_price,
                    'freight_amount' => $item->freight_amount,
                    'manifest_fee' => $item->manifest_fee,
                    'hawb_fee' => $item->hawb_fee,
                    'other_fee' => $item->other_fee,
                    'currency' => $item->currency,
                    'created_at' => $item->created_at->format('Y-m-d H:i:s'),
                ];
            });

        // 计算总金额
        return $this->success([
            'list' => $items,
            'total' => $total,
        ]);
    }

    /**
     * 添加航司运费
     */
    public function add(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'agent_id' => 'required|integer|min:1',
            'take_order' => 'required',
            'flight_date' => 'required|date',
            'package_num' => 'required|integer|min:0',
            'origin' => 'required|string',
            'destination' => 'required|string',
            'weight' => 'required|numeric|min:0',
            'charge_weight' => 'required|numeric|min:0',
            'unit_price' => 'required|numeric|min:0',
            'freight_amount' => 'required|numeric|min:0',
            'manifest_fee' => 'required|numeric|min:0',
            'hawb_fee' => 'required|numeric|min:0',
            'other_fee' => 'required|numeric|min:0',
            'currency' => 'required',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        // 验证供应商是否存在且为航司运输类型
        $agent = AgentModel::find($request->input('agent_id'));
        if (!$agent) {
            return $this->error('供应商不存在');
        }

        if ($agent->type != AgentModel::AGENT_TYPE_AIRLINE) {
            // return $this->error('供应商类型必须为航司运输');
        }

        // 验证主单是否存在
        $takeOrder = TakeOrderModel::where('sn', $request->input('take_order'))->first();
        if (!$takeOrder) {
            return $this->error('主单不存在');
        }

        $auth = $request->get('auth');

        try {
            $airlineFreight = new PayableAirlineModel();
            $airlineFreight->agent_id = $request->input('agent_id');
            $airlineFreight->take_order_id = $takeOrder->id;
            $airlineFreight->flight_date = $request->input('flight_date');
            $airlineFreight->package_num = $request->input('package_num');
            $airlineFreight->origin = $request->input('origin');
            $airlineFreight->destination = $request->input('destination');
            $airlineFreight->weight = $request->input('weight');
            $airlineFreight->charge_weight = $request->input('charge_weight');
            $airlineFreight->unit_price = $request->input('unit_price');
            $airlineFreight->freight_amount = $request->input('freight_amount');
            $airlineFreight->manifest_fee = $request->input('manifest_fee');
            $airlineFreight->hawb_fee = $request->input('hawb_fee');
            $airlineFreight->other_fee = $request->input('other_fee');
            $airlineFreight->currency = $request->input('currency');
            $airlineFreight->status = PayableAirlineModel::STATUS_UNPAID;
            $airlineFreight->pay_amount = 0;
            $airlineFreight->remarks = trim($request->input('remarks', ''));
            $airlineFreight->created_admin_id = $auth->id;
            $airlineFreight->save();

            return $this->success($airlineFreight);
        } catch (\Exception $e) {
            return $this->error('添加失败：' . $e->getMessage());
        }
    }

    /**
     * 更新航司运费
     */
    public function update(Request $request, $id)
    {
        $airlineFreight = PayableAirlineModel::find($id);
        if (!$airlineFreight) {
            return $this->error('航司运费记录不存在');
        }

        $validator = Validator::make($request->all(), [
            'agent_id' => 'required|integer|min:1',
            'take_order' => 'required',
            'flight_date' => 'required|date',
            'package_num' => 'required|integer|min:0',
            'origin' => 'required|string',
            'destination' => 'required|string',
            'weight' => 'required|numeric|min:0',
            'charge_weight' => 'required|numeric|min:0',
            'unit_price' => 'required|numeric|min:0',
            'freight_amount' => 'required|numeric|min:0',
            'manifest_fee' => 'required|numeric|min:0',
            'hawb_fee' => 'required|numeric|min:0',
            'other_fee' => 'required|numeric|min:0',
            'currency' => 'required',
        ]);

        if ($validator->fails()) {
            return $this->error($validator->errors()->first());
        }

        // 验证供应商是否存在且为航司运输类型
        $agent = AgentModel::find($request->input('agent_id'));
        if (!$agent) {
            return $this->error('供应商不存在');
        }

        if ($agent->type != AgentModel::AGENT_TYPE_AIRLINE) {
            // return $this->error('供应商类型必须为航司运输');
        }

        // 验证主单是否存在
        $takeOrder = TakeOrderModel::where('sn', $request->input('take_order'))->first();
        if (!$takeOrder) {
            return $this->error('主单不存在');
        }

        try {
            $airlineFreight->agent_id = $request->input('agent_id');
            $airlineFreight->take_order_id = $takeOrder->id;
            $airlineFreight->flight_date = $request->input('flight_date');
            $airlineFreight->package_num = $request->input('package_num');
            $airlineFreight->origin = $request->input('origin');
            $airlineFreight->destination = $request->input('destination');
            $airlineFreight->weight = $request->input('weight');
            $airlineFreight->charge_weight = $request->input('charge_weight');
            $airlineFreight->unit_price = $request->input('unit_price');
            $airlineFreight->freight_amount = $request->input('freight_amount');
            $airlineFreight->manifest_fee = $request->input('manifest_fee');
            $airlineFreight->hawb_fee = $request->input('hawb_fee');
            $airlineFreight->other_fee = $request->input('other_fee');
            $airlineFreight->currency = $request->input('currency');
            $airlineFreight->remarks = trim($request->input('remarks', ''));
            $airlineFreight->save();

            return $this->success($airlineFreight);
        } catch (\Exception $e) {
            return $this->error('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 删除航司运费
     */
    public function delete($id)
    {
        $airlineFreight = PayableAirlineModel::find($id);
        if (!$airlineFreight) {
            return $this->error('航司运费记录不存在');
        }

        if ($airlineFreight->status != PayableAirlineModel::STATUS_UNPAID) {
            return $this->error('已付款的记录不能删除');
        }

        try {
            $airlineFreight->delete();
            return $this->success(true);
        } catch (\Exception $e) {
            return $this->error('删除失败：' . $e->getMessage());
        }
    }

} 